﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace BleQua.UI {
	/// <summary>
	/// Interaction logic for LoginWindow.xaml
	/// </summary>
	public partial class LoginWindow : Window {
		private BackgroundWorker backWorker;
		private string oldTitle;
		public LoginWindow( ) {
			InitializeComponent( );
			this.backWorker = new BackgroundWorker( );
			this.backWorker.WorkerReportsProgress = true;
			this.backWorker.WorkerSupportsCancellation = true;
			this.backWorker.DoWork += backWorker_DoWork;
			this.backWorker.RunWorkerCompleted += backWorker_RunWorkerCompleted;
			this.comboBoxProfiles.Focus( );
		}

		protected void ReloadProfiles( ) {
			var path = AppInfo.ExecutablePath.DirectoryName + @"\Profiles\";
			var extension = ".sdf";
			if (System.IO.Directory.Exists(path)) {
				var items = from item in System.IO.Directory.GetFiles(path, "*" + extension)
							select System.IO.Path.GetFileNameWithoutExtension(item);
				this.comboBoxProfiles.ItemsSource = items;
			} else
				System.IO.Directory.CreateDirectory(path);
		}

		private void Window_Loaded(object sender, RoutedEventArgs e) {
			this.ReloadProfiles( );
		}

		private void TB_KeyDown(object sender, KeyEventArgs e) {
			if (e.Key == Key.Enter)
				buttonLogin_Click(sender, e);
		}

		private void buttonCancel_Click(object sender, RoutedEventArgs e) {
			this.Close( );
		}

		private void buttonLogin_Click(object sender, RoutedEventArgs e) {
			this.LayoutRoot.IsEnabled = false;
			this.oldTitle = this.Title;
			this.Title += "...";
			this.progressBarStatus.Visibility = Visibility.Visible;
			this.progressBarStatus.IsIndeterminate = true;
			if (this.comboBoxProfiles.SelectedItem is string)
				App.DataSource.Username = (string)this.comboBoxProfiles.SelectedItem;
			App.DataSource.Password = this.passwordBoxPassword.Password;
			if (!this.backWorker.IsBusy)
				this.backWorker.RunWorkerAsync( );
		}

		private void backWorker_DoWork(object sender, DoWorkEventArgs e) {
			object username = this.Username;
			string password = this.Password;

			if (this.comboBoxProfiles.Items.Count == 0)
				MessageBox.Show("Nie znaleziono profili użytkowników!", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
			else if (!(username is string))
				MessageBox.Show("Wybierz swój profil!", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
			else if (!System.IO.File.Exists(AppInfo.ExecutablePath.DirectoryName + @"\Profiles\" + (string)username + ".sdf"))
				MessageBox.Show("Wybrany profil nie istnieje!", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
			else {
				try {
					App.DataSource.LoadDatabase( );
				} catch (Exception ex) {
					if (ex.InnerException != null)
						MessageBox.Show(ex.InnerException.Message, "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
					else
						MessageBox.Show(ex.Message, "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
				}
			}
		}

		private void backWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
			this.progressBarStatus.Visibility = Visibility.Hidden;
			this.LayoutRoot.IsEnabled = true;
			this.Title = oldTitle;
			if (App.DataSource.IsLoaded) {
				this.IsEnabled = false;
				this.passwordBoxPassword.Password = "";
				MainWindow mainWindow = new MainWindow( );
				mainWindow.Owner = this;
				mainWindow.Show( );
				mainWindow.Closed += mainWindow_Closed;
				this.Visibility = Visibility.Collapsed;
			}
		}

		void mainWindow_Closed(object sender, EventArgs e) {
			if (sender is Window) {
				Window main = (Window)sender;
				main.Closed -= this.mainWindow_Closed;
				main.Owner = null;
			}
			if (this.Visibility == Visibility.Hidden) {
				App.DataSource.UnloadData( );
				this.IsEnabled = true;
				this.Visibility = Visibility.Visible;
				this.comboBoxProfiles.Focus( );
			} else {
				App.Current.Shutdown( );
			}
		}

		delegate string GetStringValue( );
		delegate object GetObjectValue( );
		delegate void VoidFunction( );

		private object Username {
			get {
				if (!this.Dispatcher.CheckAccess( )) {
					return this.Dispatcher.Invoke(new GetObjectValue(delegate {
						return this.comboBoxProfiles.SelectedItem;
					}));
				} else
					return this.comboBoxProfiles.SelectedItem;
			}
		}

		private string Password {
			get {
				if (!this.Dispatcher.CheckAccess( )) {
					object obj = this.Dispatcher.Invoke(new GetStringValue(delegate {
						return this.passwordBoxPassword.Password;
					}));
					return obj as string;
				} else
					return this.passwordBoxPassword.Password;
			}
		}
	}
}
